<template>
  <div class="movie-detail">
    <div class="container movie-detail-container">
      <div v-if="loading" class="text-center my-5">
        <div class="spinner-border text-primary" role="status">
          <span class="sr-only">Loading...</span>
        </div>
        <p class="mt-2">Loading movie details...</p>
      </div>
      
      <div v-else-if="error" class="alert alert-danger text-center" role="alert">
        <h4 class="alert-heading">Error loading movie</h4>
        <p>{{ error }}</p>
        <button @click="fetchMovie" class="btn btn-primary">Try Again</button>
      </div>
      
      <div v-else-if="movie" class="row">
        <div class="col-md-8">
          <div class="video-player">
            <video 
              v-if="movie.videoUrl" 
              controls 
              autoplay 
              style="width: 100%; height: auto;"
              controlsList="nodownload"
            >
              <source :src="movie.videoUrl" type="video/mp4">
              Your browser does not support the video tag.
            </video>
            <div v-else class="no-video text-center p-5">
              <div class="display-1 text-muted">🎬</div>
              <h3 class="mt-3">Video not available</h3>
              <p class="lead">This movie doesn't have a video URL configured yet.</p>
            </div>
          </div>
        </div>
        <div class="col-md-4">
          <div class="movie-info">
            <img :src="movie.coverImageUrl || 'https://via.placeholder.com/300x400?text=No+Image'" 
                 class="img-fluid rounded mb-4" 
                 :alt="movie.title"
                 style="width: 100%;">
            <h1>{{ movie.title }}</h1>
            <p><strong>Year:</strong> {{ movie.year }}</p>
            <p><strong>Director:</strong> {{ movie.director }}</p>
            <p><strong>Genre:</strong> {{ movie.genre }}</p>
            <p><strong>Duration:</strong> {{ formatDuration(movie.duration) }}</p>
            <p>
              <strong>Rating:</strong> 
              <span class="rating">{{ movie.rating }}/10</span>
              <span class="stars ml-2">
                <span v-for="n in 5" :key="n" class="star">
                  {{ n <= Math.floor(movie.rating/2) ? '★' : '☆' }}
                </span>
              </span>
            </p>
            <p><strong>Description:</strong></p>
            <p class="movie-description">{{ movie.description }}</p>
            
            <div class="mt-4">
              <button class="btn btn-primary mr-2" @click="goBack">Back to Movies</button>
              <button @click="toggleFavorite" class="btn mr-2" 
                      :class="isFavorite ? 'btn-danger' : 'btn-outline-danger'">
                {{ isFavorite ? '❤️ Favorited' : '🤍 Add to Favorites' }}
              </button>
              <button class="btn btn-outline-primary" @click="shareMovie">Share</button>
            </div>
          </div>
        </div>
      </div>
      
      <div v-else class="text-center my-5">
        <h3>Movie not found</h3>
        <button class="btn btn-primary" @click="goBack">Back to Movies</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import store from '../store'

export default {
  name: 'MovieDetail',
  props: ['id'],
  data() {
    return {
      movie: null,
      loading: true,
      error: null,
      isFavorite: false
    }
  },
  mounted() {
    this.fetchMovie()
  },
  methods: {
    fetchMovie() {
      this.loading = true
      this.error = null
      axios.get(`http://localhost:8080/api/movies/${this.id}`)
        .then(response => {
          this.movie = response.data
          this.isFavorite = store.isFavorite(this.movie.id)
          this.loading = false
        })
        .catch(error => {
          console.error('Error fetching movie:', error)
          this.error = 'Failed to load movie details. Please try again later.'
          this.loading = false
        })
    },
    goBack() {
      this.$router.push('/')
    },
    formatDuration(minutes) {
      const hours = Math.floor(minutes / 60)
      const mins = minutes % 60
      if (hours > 0) {
        return `${hours}h ${mins}m`
      }
      return `${mins}m`
    },
    shareMovie() {
      if (navigator.share) {
        navigator.share({
          title: this.movie.title,
          text: this.movie.description,
          url: window.location.href
        }).catch(error => {
          console.log('Sharing failed', error);
        });
      } else {
        // Fallback for browsers that don't support Web Share API
        this.copyToClipboard(window.location.href);
      }
    },
    copyToClipboard(text) {
      const el = document.createElement('textarea');
      el.value = text;
      document.body.appendChild(el);
      el.select();
      document.execCommand('copy');
      document.body.removeChild(el);
      alert('Link copied to clipboard!');
    },
    toggleFavorite() {
      if (this.isFavorite) {
        store.removeFavorite(this.movie.id)
      } else {
        store.addFavorite(this.movie.id)
      }
      this.isFavorite = !this.isFavorite
    }
  }
}
</script>

<style scoped>
.rating {
  font-size: 1.2em;
  font-weight: bold;
  color: #ff6b6b;
}

.stars {
  color: #ffc107;
}

.movie-description {
  white-space: pre-line;
  line-height: 1.6;
}

/* 样式已移至全局样式文件 */
</style>